# -*- coding: utf-8 -*-
from django.core.cache import cache
from django.core.mail import send_mail

from django.db import models
from django.db.models.fields.related import OneToOneField, ManyToManyField
from django.template.loader import render_to_string
from django.utils.datetime_safe import datetime
from registration.models import User

import datetime as dt
from messages.models import Message
import settings

SEX_CHOICES = [
    (0, u'женский'),
    (1, u'мужской'),
]

class GlobalType(models.Model):
    name = models.CharField(u"Тип (авто, туризм или стиль)", max_length=20)
    def __unicode__(self):
        return self.name
    class Meta:
        verbose_name = u'Тип(авто, туризм, стиль)'
        verbose_name_plural = u'Типы'
    


class Country(models.Model):
  name = models.CharField(u'Страна', max_length=24, unique=True)
  def __unicode__(self):
    return self.name
  class Meta:
    verbose_name = u'страна'
    verbose_name_plural = u'страны'
    #ordering = ["name"]




class City(models.Model):
    country = models.ForeignKey(Country)
    name = models.CharField(u'Город', max_length=36)
    def __unicode__(self):
        return self.name
    class Meta:
        verbose_name = u'город'
        verbose_name_plural = u'города'
        ordering = ["country", "name"]

class Area(models.Model):
    name = models.CharField(u'Область', max_length=36)
    def __unicode__(self):
        return self.name
    class Meta:
        verbose_name = u'Область'
        verbose_name_plural = u'Области'
        ordering = ["name",]

class Activity(models.Model):
    name = models.CharField(u"Название", max_length = 64)
    def __unicode__(self):
        return self.name
    class Meta:
        verbose_name = u'вид деятельности'
        verbose_name_plural = u'виды деятельности'

class Category(models.Model):
    name = models.CharField(u"Название", max_length = 64)
    type = models.ForeignKey(GlobalType)
    def __unicode__(self):
        return self.name
    class Meta:
        verbose_name = u'Категория'
        verbose_name_plural = u'Категории'


class Company(models.Model):
    name = models.CharField(u'Название', max_length=36)
    phone = models.CharField(u"Телефон", max_length = 36, null = True, blank = True)
    worktime = models.CharField(u"Время работы", max_length=50, null = True, blank=True)
    website = models.CharField(u"Сайт", max_length=50, null = True, blank=True)
    description = models.TextField(u"Описание", null = True, blank = True)
    partners = models.ManyToManyField("self", verbose_name=u"партнёры", null = True, blank = True)
    categories = models.ManyToManyField(Category, related_name="category_companies", verbose_name=u"Категории", null = True, blank=True)
    activities = models.ManyToManyField(Activity, verbose_name=u"Сферы деятельности", null = True, blank=True)
    ownership_type = models.CharField(u'Форма собственности', max_length=50)
    fiz_address = models.CharField(u'Физ. адрес', max_length=150)
    ur_address = models.CharField(u'Юр. адрес', max_length=150)
    logo  = models.ImageField(u"Логотип:", upload_to="upload/user_files",blank=True, null=True)
    owner = models.ForeignKey(User, verbose_name=u"Владелец", related_name="companies")
    country = models.ForeignKey(Country, verbose_name="*Страна:", blank=True, null=True)
    city = models.ForeignKey(City, verbose_name=u"*Город:", blank=True, null=True)
    area = models.ForeignKey(Area, verbose_name=u"Область:", blank=True, null=True)
    phone = models.CharField(u"Телефон:", max_length=16, blank=True, null=True)
    icq = models.BigIntegerField(u"ICQ:", blank=True, null=True)
    skype = models.CharField(u"Skype:", max_length=32, blank=True, null=True)
    website = models.CharField(u"Сайт:", max_length=32, blank=True, null=True)
    email = models.EmailField(u"E-mail:",  blank=True, null=True)
    users = models.ManyToManyField(User, related_name="user_companies", verbose_name=u"Клиенты", null = True, blank=True)
    type = models.ForeignKey(GlobalType)
    def __unicode__(self):
        return self.name
    class Meta:
        verbose_name = u'Компания'
        verbose_name_plural = u'Компании'


class Good(models.Model):
    name = models.CharField(u'Название', max_length=36)
    image = models.ImageField(u"Изображение", upload_to="upload/user_files", null = True, blank = True)
    description = models.CharField(u'Описание', max_length=100, null = True, blank = True)
    price = models.IntegerField(u"Цена", null = True, blank= True)
    company= models.ForeignKey(Company, related_name="goods")
    def __unicode__(self):
        return self.name
    class Meta:
        verbose_name = u'товар'
        verbose_name_plural = u'товары'

        
class DiscussionMessage(models.Model):
    text = models.TextField(u"Текст")
    publisher = models.ForeignKey(User, related_name="duscussion_messages")
    post_date = models.DateTimeField(u"Дата опубликования", default=datetime.now())
    class Meta:
        verbose_name = u'Сообщение из обсуждений'
        verbose_name_plural = u'Сообщения обсуждений'


class Discussion(models.Model):
    subj = models.CharField(u'Тема', max_length=36)
    messages = models.ManyToManyField(DiscussionMessage, null = True, blank=True, related_name = "discussion")
    type = models.ForeignKey(GlobalType)
    creation_date = models.DateTimeField(u"Дата опубликования", default=datetime.now())
    creator = models.ForeignKey(User, related_name="user_duscussions")
    class Meta:
        verbose_name = u'Обсуждение'
        verbose_name_plural = u'Обсуждения'

    def get_last_post(self):
        try:
            ms = self.messages.all().order_by("-id")
        except Exception, e:
            ms = None
            #print e
        if ms:
            return ms[0]
        else:
            return None

    def get_first_post(self):

        try:
            ms = self.messages.all().order_by("id")
        except:
            ms = None
        if ms:
            return ms[0]
        else:
            return None



class ImageLoadClass(models.Model):
    image = models.ImageField("Image:", upload_to="upload/user_files",blank=True, null=True)


class UserInfo(models.Model):
    user = OneToOneField(User, related_name = "user_info", blank=True, null=True)
    first_name =models.CharField(u"Имя", max_length=50, blank=True, null=True)
    last_name =models.CharField(u"Фамилия", max_length=50, blank=True, null=True)
    sex = models.PositiveSmallIntegerField('*Пол:', choices=SEX_CHOICES, blank=True, null=True)
    birthday = models.DateField(u"*Дата рождения:", blank=True, null=True)
    country = models.ForeignKey(Country, verbose_name="*Страна:", blank=True, null=True)
    city = models.ForeignKey(City, verbose_name="*Город:", blank=True, null=True)
    area = models.ForeignKey(Area, verbose_name="Область:", blank=True, null=True)
    friends = ManyToManyField(User, null = True, blank = True, verbose_name="Друзья")
    phone = models.CharField(u"Телефон:", max_length=16, blank=True, null=True)
    icq = models.BigIntegerField("ICQ:", blank=True, null=True)
    skype = models.CharField(u"Skype:", max_length=32, blank=True, null=True)
    vkontakte = models.CharField(u"Вконтакте id:", max_length=32, blank=True, null=True)
    website = models.CharField(u"Сайт:", max_length=32, blank=True, null=True)
    email = models.EmailField(u"E-mail:",  blank=True, null=True)
    contacts = models.TextField(u"Контактные данные:", blank=True, null=True)
    avatar = models.ImageField(u"Аватар:", upload_to="upload/user_files",blank=True, null=True)
    #companies = models.ManyToManyField(Company, blank = True, null = True, related_name = "owner")
    status = models.CharField(u"Статус:", max_length=100, blank=True, null=True)
    my_auto = models.CharField(u"Мой автомобиль:", max_length=50, blank=True, null=True)

    #notify = models.BooleanField("Уведомлять по эл. почте о предложении дружбы:", default=False)
    #settings = models.ForeignKey(PrivateSettings, null = True)
    #notify_settings = models.ForeignKey(NotifySettings, null = True)


    def __unicode__(self):
        return self.user.username

    def get_age(self):
        d2 = datetime.date.today()
        d1 = self.birthday
        age = (d2.year - d1.year) - int((d2.month, d2.day) < (d1.month, d1.day))
        return age
    

    def get_txt(self):
        age = self.get_age()
        ext = age % 10
        if ext == 1:
          txt = u"год"
        elif ext in (2, 3, 4) and (age > 10) and (age < 20):
          txt = u"лет"
        elif ext in (2, 3, 4):
          txt = u"года"
        else:
          txt= u"лет"
        return txt

    def last_seen(self):
        return cache.get('seen_%s' % self.user.username)

    def online(self):
        if self.last_seen():
            now = datetime.now()
            if now > self.last_seen() + dt.timedelta(
                         seconds=settings.USER_ONLINE_TIMEOUT):
                return False
            else:
                return True
        else:
            return False

    def get_unreaded_messages(self):
        return Message.objects.filter(recipient= self.user, read_at__isnull = True)

    class Meta:
        verbose_name = u'Информация о пользователе'
        verbose_name_plural = u'Информация о пользователях'




class WallMessage(models.Model):
    """
    Сообщение на стене
    """
    text = models.TextField(u"Текст сообщения")
    sender = models.ForeignKey(User)
    recipient = models.ForeignKey(User, related_name='wall_messages', null=True, blank=True)
    sent_at = models.DateTimeField(u"Дата отправления", default = datetime.now())
    def __unicode__(self):
        return self.text
    class Meta:
        ordering=["-id"]
        verbose_name = u'Запись на стене'
        verbose_name_plural = u'Записи на стенах'


class Offer(models.Model):
    """
    Предложение от компании
    """
    text = models.TextField(u"Текст")
    company = models.ForeignKey(Company, related_name="offers")
    class Meta:
        ordering=["-id"]
        verbose_name = u'Предложение'
        verbose_name_plural = u'Предложения'

class Order(models.Model):
    """
    Заказ
    """
    subj = models.CharField(u"Заголовок", max_length=100)
    text = models.TextField(u"Текст")
    price = models.IntegerField(u"Бюджет", null = True, blank=True)
    user = models.ForeignKey(User, related_name="offers")
    type = models.ForeignKey(GlobalType)
    active =models.BooleanField(u"Активен?", default=True)
    order_date = models.DateTimeField(default=datetime.now())
    class Meta:
        ordering=["-id"]
        verbose_name = u'Заказ'
        verbose_name_plural = u'Заказы'


class ResponseToOrder(models.Model):
    """
    Ответ на заказ
    """
    order = models.ForeignKey(Order, verbose_name=u"Заказ", related_name="responses")
    company = models.ForeignKey(Company)
    text = models.TextField(u"Текст")
    response_date = models.DateTimeField(default=datetime.now())
    active =models.BooleanField(u"Активен?", default=True)
    class Meta:
        ordering=["-id"]
        verbose_name = u'Ответ на заказ'
        verbose_name_plural = u'Ответы на заказы'


    def accept(self):
        """
        Принять. Назначить предендента исполнителем,отправить ему емейл об этом
        """
        self.order.active = False
        self.order.save()
        try:
            self.company.owner.notify_settings.all()[0].send_notify_order_response(self.order, self.company)
        except:
            pass


    def decline(self):
        self.active = False
        self.save()
        """
        Отвергнуть предложение претендента
        """
        pass


class NotifySettings(models.Model):
    """
    Настройки оповещений
    """
    user = models.ForeignKey(User, related_name="notify_settings")
    notify_friends = models.BooleanField(default = True)
    notify_order_response = models.BooleanField(default = True)
    notify_new_companies = models.BooleanField(default = True)
    notify_wall_comments = models.BooleanField(default= True)
    class Meta:
        verbose_name = u'Настройки оповещений'
        verbose_name_plural = u'Настройки оповещений'

    def send_notify_friends(self, possible_friend):
        '''
        Отправить оповещение о предложении дружбы
        '''
        if self.notify_friends:
            email = self.user.email
            subj = u'Проект Мы. Приглашение в друзья'
            text = u"Пользователь %s %s приглашает Вас стать его другом"%(possible_friend.user_info.last_name, possible_friend.user_info.first_name)
            try:
                send_mail(subj, text, email,(email,), fail_silently=True)
            except:
                pass

    def send_notify_order_response(self, order, company):
        """
        Отправить оповещение, что предложение пользователя на заказ принято
        """
        if self.notify_order_response:
            email = order.user.email
            subj = u'Проект Мы. Сообщение от %s %s (%s)' %(order.user.last_name, order.user.first_name, order.user.email)
            text = render_to_string("letter_template.txt", {'order':order})
            try:
                send_mail(subj, text, email,(company.owner.email,), fail_silently=True)
            except:
                pass


    def send_notify_new_companies(self, company):
        """
        Отправить оповещение, что добавлена новая компания
        """
        if self.notify_new_companies:
            email = self.user.email
            subj = u'Проект Мы. Новая компания'
            text = u"Добавлена компания %s"%company.name
            try:
                send_mail(subj, text, email,(company.owner.email,), fail_silently=True)
            except:
                pass

    def send_notify_wall_comments(self, wall_message):
        """
        Отправить оповещение о записи на стене
        """
        if self.notify_wall_comments:
           email = wall_message.sender.email
           subj = u'Проект Мы. Пользователь %s %s написал что-то на Вашей стене'%(wall_message.sender.last_name, wall_message.sender.first_name)
           text = u"%s"%wall_message.text
           try:
               send_mail(subj, text, email,(wall_message.recipient.email,), fail_silently=True)
           except:
               pass
           
           




    